import editForm from "../form.vue";
import permissionForm from "../permission.vue";
import {
  type Role,
  addRole,
  updateRole,
  deleteRole,
  getRoleList,
  bindPermission
} from "@/api/system";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { DictTag } from "@/components/ReDict";
import { ElMessageBox } from "element-plus";

export function userRole() {
  const form = reactive<Role>({
    current: 1,
    size: 20
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1
  });
  const columns: TableColumnList = [
    {
      label: "角色名称",
      prop: "name",
      width: 200
    },
    {
      label: "角色代码",
      prop: "code",
      width: 200
    },
    {
      label: "角色说明",
      prop: "description"
    },
    {
      label: "状态",
      prop: "state",
      width: 80,
      cellRenderer: ({ row, props }) => (
        <DictTag size={props.size} value={row.state} code="State" />
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 250,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    form.size = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.current = val;
    onSearch();
  }

  function onSearch() {
    loading.value = true;
    getRoleList(form)
      .then(data => {
        dataList.value = data.records;
        pagination.total = data.total;
        pagination.pageSize = data.size;
        pagination.currentPage = data.current;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  const resetForm = (formEl: any) => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: Role) {
    addDialog({
      title: `${title}角色`,
      props: {
        formInline: {
          id: row?.id ?? "",
          name: row?.name ?? "",
          code: row?.code ?? "",
          value: row?.description ?? "",
          state: row?.state ?? true
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as Role;
        function add() {
          addRole(curData)
            .then(() => {
              message("角色新增成功", {
                type: "success"
              });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`角色新增失败:${err.message}`, {
                type: "error"
              });
            });
        }
        function update() {
          updateRole(curData)
            .then(() => {
              message("角色更新成功", { type: "success" });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`角色更新失败:${err}`, { type: "error" });
            });
        }
        FormRef.validate((valid: boolean) => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              add();
            } else {
              // 实际开发先调用编辑接口，再进行下面操作
              update();
            }
          }
        });
      }
    });
  }

  function openPermissionDialog(roleId: string, name: string) {
    addDialog({
      title: `分配权限-${name}`,
      destroyOnClose: true,
      props: {
        formInline: {
          roleId: roleId
        }
      },
      width: "30%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(permissionForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline;

        function submit() {
          bindPermission(curData.roleId, curData.permission)
            .then(() => {
              message("权限分配成功", { type: "success" });
              done(); // 关闭弹框
            })
            .catch(err => {
              message(`权限分配失败:${err}`, { type: "error" });
            });
        }

        if (curData.permission == null || curData.permission.length === 0) {
          ElMessageBox.confirm("确定清空该角色权限?", "警告", {
            type: "warning"
          }).then(() => {
            submit();
          });
        } else {
          submit();
        }
      }
    });
  }

  function handleDelete(row: Role) {
    deleteRole(row.id)
      .then(() => {
        message("角色删除成功", { type: "success" });
        onSearch();
      })
      .catch(err => {
        message(`角色删除失败:${err}`, { type: "error" });
      });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    onSearch,
    resetForm,
    pagination,
    openDialog,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    openPermissionDialog
  };
}
